package com.guosen.zebra.framework.starter.startup.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class ActuatorFilter extends OncePerRequestFilter {

    private static final String ZEBRA_TOKEN = "ZEBRA-TOKEN";

    @Value("${management.zebra.token}")
    private String token;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String zebraToken = request.getHeader(ZEBRA_TOKEN);
        if (!token.equals(zebraToken)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("text/plain; charset=UTF-8");
            response.getWriter().write("Request validation failed");
            response.getWriter().flush();
            log.error("zebra token validation failed. request url: {}", request.getRequestURI());
            return;
        }
        filterChain.doFilter(request, response);
    }
}
